﻿using MasterDetailTemplate.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Xamarin.Forms.Extended;
using MasterDetailTemplate.Models;
using Xamarin.Forms;
using Xamarin.Plugin.Calendar.Models;

namespace MasterDetailTemplate.ViewModels {
    /// <summary>
    /// 纪念日页ViewModel。
    /// By FJH
    /// </summary>
    public class AnniversaryPageViewModel : ViewModelBase {
        /// <summary>
        /// 事件存储。
        /// </summary>
        private IEventStorage _eventStorage;

        /// <summary>
        /// 内容页导航。
        /// </summary>
        private IContentNavigationService _contentNavigationService;

        /// <summary>
        /// 根导航。
        /// </summary>
        private IRootNavigationService _rootNavigationService;

        /// <summary>
        /// 纪念日的集合（按照日期分）。
        /// </summary>
        private EventCollection _events;

        public EventCollection Events
        {
            get { return _events; }
            set
            {
                _events = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 所有纪念日列表。
        /// </summary>
        public List<Event> MemoryDayList { get; set; }

        /// <summary>
        /// 事件字典。
        /// </summary>
        public Dictionary<DateTime, List<Event>> eventsDictionary { get; set; }

        /// <summary>
        /// 查询功能。
        /// </summary>
        private ICommand _searchCommand;

        /// <summary>
        /// 查询功能。
        /// </summary>
        public ICommand SearchCommand =>
            _searchCommand ?? (_searchCommand = new Command(async () =>
                await SearchCommandFunction()));

        public async Task SearchCommandFunction() =>
            await _contentNavigationService.NavigateToAsync(
                ContentNavigationConstants.AnniversarySearchPage);

        /// <summary>
        /// 收藏点击功能。
        /// </summary>
        private RelayCommand<Event> _stickDayCommand;

        /// <summary>
        /// 收藏点击功能。
        /// </summary>
        public RelayCommand<Event> StickDayCommand =>
            _stickDayCommand ?? (_stickDayCommand =
                new RelayCommand<Event>(async @event =>
                    await StickDayCommandFunction(@event)));

        public async Task StickDayCommandFunction(Event eEvent) {
            eEvent.IsImportant = eEvent.IsImportant == 1 ? 0 : 1;
            eEvent.DateStamp = DateTime.Now.Ticks;
            await _eventStorage.SaveEventAsync(eEvent);
        }

        /// <summary>
        /// 纪念日点击命令。
        /// </summary>
        public RelayCommand<Event> EventTappedCommand =>
            _eventTappedCommand ?? (_eventTappedCommand =
                new RelayCommand<Event>(async @event =>
                    await EventTappedCommandFunction(@event)));

        /// <summary>
        /// 纪念日点击命令。
        /// </summary>
        private RelayCommand<Event> _eventTappedCommand;

        public async Task EventTappedCommandFunction(Event eEvent) =>
            await _contentNavigationService.NavigateToAsync(
                ContentNavigationConstants.AnniversaryDetailPage, eEvent);


        /// <summary>
        /// 将异步转换成同步，把数据放入集合
        /// </summary>
        public void FillList() {
            var sourceTask = new TaskCompletionSource<List<Event>>();
            var task1 = sourceTask.Task;
            Task.Run(async () => {
                var result = await _eventStorage.GetMemoryDaysAsync();
                sourceTask.SetResult(result);
            });


            MemoryDayList = task1.Result;
            eventsDictionary = new Dictionary<DateTime, List<Event>>();
            if (MemoryDayList != null) {
                foreach (var memoryday in MemoryDayList) {
                    if (eventsDictionary.TryGetValue(memoryday.Date,
                        out var memoryList)) {
                        memoryList.Add(memoryday);
                    } else {
                        eventsDictionary[memoryday.Date] =
                            new List<Event> {memoryday};
                    }
                }

                foreach (var memoryList in eventsDictionary) {
                    Events.Add(memoryList.Key, memoryList.Value);
                }
            }
        }

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand =
                new RelayCommand(() => {
                    Events = new EventCollection();
                    FillList();
                }));

        /// <summary>
        /// 纪念日页的viewmodel。
        /// </summary>
        /// <param name="eventStorage">事件存储。</param>
        /// <param name="contentNavigationService">内容页导航服务。</param>
        /// <param name="rootNavigationService">根导航服务。</param>
        public AnniversaryPageViewModel(IEventStorage eventStorage,
            IContentNavigationService contentNavigationService,
            IRootNavigationService rootNavigationService) {
            _eventStorage = eventStorage;
            _contentNavigationService = contentNavigationService;
            _rootNavigationService = rootNavigationService;
            MemoryDayList = new List<Event>();
            Events = new EventCollection();
        }
    }
}